from rest_framework import serializers

from apps.goods.models import SKU, SKUSpecification, GoodsCategory, SPUSpecification, SpecificationOption


class SKUSpecificationSerialzier(serializers.ModelSerializer):
    """
    SKU规格表序列化器
    """
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ("spec_id", 'option_id')


class SKUGoodSeralizer(serializers.ModelSerializer):
    specs = SKUSpecificationSerialzier(many=True)
    # 指定分类信息
    category_id = serializers.IntegerField()
    # 关联嵌套返回
    category = serializers.StringRelatedField(read_only=True)
    # 指定所关联的spu表信息
    spu_id = serializers.IntegerField()
    # 关联嵌套返回
    spu = serializers.StringRelatedField()

    class Meta:
        model = SKU
        fields = '__all__'
    #
    # def create(self, validated_data):
    #     specs = self.context['request'].data.get('specs')
    #     sku =SKU.objects.create(**validated_data)
    #     for specs in specs:
    #         SKUSpecification.objects.create(sku=sku,spec_id=specs['spec_id'],option_id=specs['option_id'])
    #     return sku

    def update(self, instance, validated_data):
        print('**********************')
        print('**********************')
        print(validated_data)
        specs = self.context['request'].data.get('specs')
        SKU.objects.filter(id=instance.id).update(**validated_data)
        for spec in specs:
            SKUSpecification.objects.create(sku=instance,spec_id=specs['spec_id'],option_id=spec['option_id'])
        return instance
    def create(self, validated_data):
        specs = validated_data.pop('specs')
        sku = super().create(validated_data)
        for item in specs:
            item['sku_id']=sku.id
            SKUSpecification.objects.create(**item)
        return sku


class SKUCategorieSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = "__all__"


class SPUOptineSerializer(serializers.ModelSerializer):
    """
    规格选项序列化器
    """

    class Meta:
        model = SpecificationOption
        fields = ('id', 'value')


class SPUSpecSerialzier(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    options = SPUOptineSerializer(read_only=True, many=True)

    class Meta:
        model = SPUSpecification
        fields = "__all__"




